/**
 * Copyright (c) 2017-2018, wangxue (3342668830@qq.com).
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jfast.framework.web.core;

import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.jfast.framework.Jfast;
import com.jfast.framework.web.handler.Handler;
import com.jfast.framework.web.session.RequestContext;

/**
 * jfast核心处理器
 * @author zengjintao
 * @version 1.0
 * 2017年10月15日下午9:54:28
 */
@WebServlet(name="jfastCoreHttpServlet", urlPatterns="/*", loadOnStartup = 0)
public class JfastCoreHttpServlet extends HttpServlet {

    private int contextPathLength;

    private Handler handler;

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        String contextPath = servletConfig.getServletContext().getContextPath();//  /Jfast
        Jfast.setContextPath(contextPath);
        contextPathLength = (contextPath == null || "/".equals(contextPath) ? 0 : contextPath.length());
        handler = Jfast.getHandler();
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding(JfastConstant.ENCODING_DEFAULT);
        response.setCharacterEncoding(JfastConstant.ENCODING_DEFAULT);
        String target = request.getRequestURI();//
        if (contextPathLength != 0) {
            target = target.substring(contextPathLength);
        }
        RequestContext.getRequestManager().handle(request, response);
        handler.doHandler(target, request, response);//开始请求
    }
}
